package com.ikai.ruderesponser;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

/**
 * Servlet that handles the creation of Rudenesses.
 * 
 * @author Ikai Lan <ikai@google.com>
 * 
 */
@SuppressWarnings("serial")
public class CreateRudenessServlet extends HttpServlet {

    public void doPost(HttpServletRequest req, HttpServletResponse resp)
	    throws IOException {
	UserService userService = UserServiceFactory.getUserService();
	User user = userService.getCurrentUser();
	if (user != null) {
	    String body = req.getParameter("body");
	    Entity rudeness = new Entity("Rudeness");
	    rudeness.setProperty("creatorId", user.getUserId());
	    rudeness.setUnindexedProperty("body", body);
	    rudeness.setProperty("useCount", 0);

	    DatastoreService datastore = DatastoreServiceFactory
		    .getDatastoreService();
	    datastore.put(rudeness);
	    resp.sendRedirect("/");
	} else {
	    resp.sendRedirect(userService.createLoginURL("/"));
	}

    }

}
